package com.shenganyuan.smac.leave;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.model.LatLng;
import com.oklib.utils.calculate.ArithUtil;
import com.oklib.utils.helper.RxUtil;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.subscriber.ApiCallbackSubscriber;
import com.oklib.utils.view.SnackbarUtil;
import com.oklib.utils.view.ToastUtils;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.beans.BaseBoolResult;
import com.shenganyuan.smac.common.data.Api;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 隐患信息录入
 *
 * @author Damon
 */

public class ActLeave extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.common_toolbar_center_title)
    TextView commonToolbarCenterTitle;
    @BindView(R.id.action_save)
    TextView actionSave;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_send)
    EditText etSend;

    private WifiManager mWifiManager;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private LatLng mlocation;

    @Override
    public int getLayoutId() {
        return R.layout.act_leave;
    }

    @Override
    public void initUI(Bundle savedInstanceState) {

    }


    @Override
    public void initData() {
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //初始化定位
        initLocation();
        //开始定位
        startLocation();
    }

    /**
     * 初始化定位，设置回调监听
     */
    private void initLocation() {
        //初始化client
        mlocationClient = new AMapLocationClient(this.getApplicationContext());
        // 设置定位监听
        mlocationClient.setLocationListener(this);
    }

    /**
     * 设置定位参数
     *
     * @return 定位参数类
     */
    private AMapLocationClientOption getOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setLocationCacheEnable(false);//设置是否返回缓存中位置，默认是true
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        return mOption;
    }

    /**
     * 检查wifi，并提示用户开启wifi
     */
    private void checkWifiSetting() {
        if (mWifiManager.isWifiEnabled()) {
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("开启WIFI模块会提升定位准确性");
        builder.setPositiveButton("去开启", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("不了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        checkWifiSetting();
        //设置定位参数
        mlocationClient.setLocationOption(getOption());
        // 启动定位
        mlocationClient.startLocation();
    }

    /**
     * 销毁定位
     */
    private void destroyLocation() {
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
            mlocationClient = null;
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    /**
     * 返回定位结果的回调
     *
     * @param aMapLocation 定位结果
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            mlocation = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        } else {
            String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
            Log.e("AmapErr", errText);
        }
    }

    @OnClick({R.id.action_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.action_save:
                saveLeaveToServer();
                break;
        }
    }

    private void saveLeaveToServer() {
        String leaveReason = etSend.getText().toString().trim();
        if (TextUtils.isEmpty(leaveReason)) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "请输入请假原因");
            return;
        }
        if (mlocation == null) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "正在获取您的位置信息请稍候");
            return;
        }
        String djuserid = App.getCurrentUser().getId();

        double longitude = mlocation.longitude;
        double latitude = mlocation.latitude ;
        longitude = ArithUtil.round(longitude, 6);
        latitude = ArithUtil.round(latitude, 6);

        String gps = longitude + ";" + latitude;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
        String qjdate = dateFormat.format(new Date());
        Map<String, String> req = new HashMap<>();
        req.put("djuserid", djuserid);
        req.put("gps", gps);
        req.put("qjdate", qjdate);
        req.put("yuanyin", leaveReason);
        req.put("token", App.getAccessToken());
        ViseHttp.RETROFIT().create(Api.class).leavesave(req)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribe(

                        new ApiCallbackSubscriber<BaseBoolResult>(new ACallback<BaseBoolResult>() {
                            @Override
                            public void onSuccess(BaseBoolResult data) {
                                try {
                                    if ("true".equalsIgnoreCase(data.getResult())) {
                                        etSend.setText("");
                                        ToastUtils.showToast(mContext, "请假信息已提交！");
                                        finish();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {
                                SnackbarUtil.showShort(getWindow().getDecorView(), "请假信息提交失败，请重试！");
                            }
                        })
                );
    }
}
